<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Invitation extends ORM {
    
    /*
     * Invitation belongs to user, 
     * 
     */

        protected $_belongs_to = array(
                    'user'    => array('model' => 'user', 'foreign_key' => 'user_id')
        );

    
        public function rules()
	{
		return array(			
			'email' => array(
				array('not_empty'),
				array('min_length', array(':value', 4)),
				array('max_length', array(':value', 127)),
				array('email'),
				array(array($this, 'email_available'), array(':validation', ':field')),
			),
		);
	}
        
        /**
	 * It triggering error if email exists.
	 * Validation callback.
	 *
	 * @param   Validation  Validation object
	 * @param   string      Field name
	 * @return  void
	 */
	public function email_available(Validation $validation, $field)
	{            
                $email_exist = DB::select()->from('invitations')
                                           ->where('email', '=', $validation[$field])
                                           ->execute()
                                           ->count();
		if ($email_exist)
		{
			$validation->error($field, 'email_available', array($validation[$field]));
		}
	}
        
        /**
        * Generates unieqe recovery token of given length.
        * @param int $length
        * @return string
        */
        public function uniqe_invitation_token($lenght = 32)
        {
            $token = Security::generate_token($lenght);
                    
            $is_uniqe = !DB::select()->from('invitations')->where('token','=',$token)->execute()->count();
                  
            if ($is_uniqe)
            {
                return $token;
            }
            else 
            {
                $this->uniqe_recovery_token($lenght);
            }
           
           
        }
    
}